﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Text.RegularExpressions;

namespace zszs
{
    /// <summary>
    /// 获取时间验证版本
    /// </summary>
    public class ValidateVersion
    {
        public int Days { get; set; }
        public DateTime beginDateTime { get; set; }
        private DateTime DateNow { get; set; }
        private bool IsPass { get; set; }
        private const string ADRESS_GETTIME = "http://www.time.ac.cn/stime.asp";
        public ValidateVersion()
        {
            this.IsPass = false;
        }
        public int Validate()
        {
            if (IsPass)
            {
                return 1;
            }
            try
            {
                WebClient wc = new WebClient();
                string resutTime = wc.DownloadString(ADRESS_GETTIME);
                // 正则表达式对象
                //'\d{4}年\d{1,2}月\d{1,2}日'
                //@"document\.write\('.*'\);"
                string YMD = Regex.Match(resutTime, @"document\.write\('(\d{4}年\d{1,2}月\d{1,2}日)?'\);").Value
                    .TrimStart(@"document\.write\('(".ToCharArray()).TrimEnd(@"?'\);".ToCharArray());

                if (YMD != null)
                {
                    DateNow = Convert.ToDateTime(YMD);
                }
                return (IsPass = (DateNow - beginDateTime).Days <= Days) ? 1 : -1;
            }
            catch (Exception)
            {
                return 0;
            }
        }
    }
}
